var http = require('http');
var fs = require('fs');
var path = require('path');
var mime = require('mime');

var cache = {};

function send404(res) {
  // body...
  res.writeHead(404, { 'Content-Type': 'text/plain' });
  res.write('Error 404');
  res.end();
}

function sendFile(res, filePath, content) {
  // body...
  res.writeHead(200, { 'Content-Type': mime.lookup(path.basename(filePath)) });
  res.end(content);
}

function serveStatic(res, cache, absPath) {
  // body...
  if (cache[absPath]) {
    sendFile(res, absPath, cache[absPath]);
  } else {
    fs.exists(absPath, function(ifExists) {
      // body...
      if (ifExists) {
        fs.readFile(absPath, function(err, data) {
          // body...
          if (err) {
            send404(res);
          } else {
            cache[absPath] = data;
            sendFile(res, absPath, data);
          }
        })
      } else {
        send404(res);
      }
    })
  }
}

var server = http.createServer(function (req,res) {
	// body..
	var filePath = false;
	if(req.url =='/'){
		filePath = 'public/index.html';
	}else{
		filePath = 'public'+req.url;
	}
	var absPath = './'+filePath;
	serveStatic(res,cache,absPath);
})

server.listen(3030,function() {
	// body...
	console.log('sever is listening to 3030 port');
})